const WebSocket = require('ws');

// WebSocket连接配置
const WS_URL = 'ws://localhost:3000/user-service/websocket';

class MountSystemTester {
    constructor() {
        this.ws = null;
        this.isConnected = false;
        this.testResults = [];
    }

    async connect() {
        return new Promise((resolve, reject) => {
            this.ws = new WebSocket(WS_URL);
            
            this.ws.on('open', () => {
                console.log('🔌 WebSocket连接成功');
                this.isConnected = true;
                resolve();
            });

            this.ws.on('error', (error) => {
                console.error('❌ WebSocket连接失败:', error.message);
                reject(error);
            });

            this.ws.on('message', (data) => {
                try {
                    const message = JSON.parse(data.toString());
                    console.log('📨 收到消息:', JSON.stringify(message, null, 2));
                    this.handleMessage(message);
                } catch (error) {
                    console.error('❌ 解析消息失败:', error.message);
                }
            });

            this.ws.on('close', () => {
                console.log('🔌 WebSocket连接已关闭');
                this.isConnected = false;
            });
        });
    }

    handleMessage(message) {
        // 处理收到的消息
        if (message.act_id) {
            console.log(`📋 指令 ${message.act_id} 响应:`, message.code === 0 ? '✅ 成功' : '❌ 失败');
            if (message.msg) {
                console.log(`💬 消息: ${message.msg}`);
            }
            if (message.data) {
                console.log(`📊 数据:`, JSON.stringify(message.data, null, 2));
            }
        }
    }

    sendCommand(command, data = null) {
        if (!this.isConnected) {
            throw new Error('WebSocket未连接');
        }

        const payload = {
            c: command,
            d: data
        };

        console.log(`📤 发送指令 ${command}:`, JSON.stringify(payload, null, 2));
        this.ws.send(JSON.stringify(payload));
    }

    async delay(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }

    // 测试获取坐骑基础列表
    async testGetMountList() {
        console.log('\n🧪 测试1: 获取坐骑基础列表 (4423)');
        this.sendCommand(4423);
        await this.delay(1000);
    }

    // 测试获取坐骑基础详情
    async testGetMountDetail() {
        console.log('\n🧪 测试2: 获取坐骑基础详情 (4421)');
        this.sendCommand(4421, { id: 1 }); // 获取战马详情
        await this.delay(1000);
    }

    // 测试获取角色坐骑列表
    async testGetCharacterMounts() {
        console.log('\n🧪 测试3: 获取角色坐骑列表 (4424)');
        this.sendCommand(4424);
        await this.delay(1000);
    }

    // 测试获取当前出战坐骑信息
    async testGetActiveMountInfo() {
        console.log('\n🧪 测试4: 获取当前出战坐骑信息 (4419)');
        this.sendCommand(4419);
        await this.delay(1000);
    }

    // 测试训练坐骑
    async testTrainMount() {
        console.log('\n🧪 测试5: 训练坐骑 (4420)');
        this.sendCommand(4420, { id: 1, t: "1" }); // 训练ID为1的坐骑
        await this.delay(1000);
    }

    // 测试设置坐骑状态
    async testSetMountStatus() {
        console.log('\n🧪 测试6: 设置坐骑状态 (4425)');
        this.sendCommand(4425, { id: 1, t: 2 }); // 设置ID为1的坐骑为出战状态
        await this.delay(1000);
    }

    // 运行所有测试
    async runAllTests() {
        try {
            await this.connect();
            
            console.log('🚀 开始坐骑系统功能测试...\n');
            
            // 执行所有测试
            await this.testGetMountList();
            await this.testGetMountDetail();
            await this.testGetCharacterMounts();
            await this.testGetActiveMountInfo();
            await this.testTrainMount();
            await this.testSetMountStatus();
            
            console.log('\n🎉 所有测试完成！');
            
            // 等待一段时间后关闭连接
            await this.delay(2000);
            this.ws.close();
            
        } catch (error) {
            console.error('❌ 测试失败:', error.message);
        }
    }
}

// 执行测试
async function main() {
    const tester = new MountSystemTester();
    await tester.runAllTests();
}

// 如果直接运行此脚本
if (require.main === module) {
    main();
}

module.exports = MountSystemTester;
